package com.lie.prepare.multi_thread.deadlock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.lie.prepare.util.Print.*;

/**
 * Created by lie on 2018/4/10.
 * 创业
 */
public class Startup {

    private Money money;
    private Product product;

    public Startup(Money money, Product product) {
        this.money = money;
        this.product = product;
    }

    public void startup1(){
        synchronized (money){
            print("先有钱");
            synchronized (product){
                print("然后有产品");
            }
        }
    }

    public void startup2(){
        synchronized (product){
            print("先有产品");
            synchronized (money){
                print("然后融到资");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();

        Startup startup = new Startup(new Money(), new Product());
        Way1 way1 = new Way1(startup);
        Way2 way2 = new Way2(startup);


        exec.execute(way1);
        TimeUnit.SECONDS.sleep(1);
        exec.execute(way2);

        exec.shutdownNow();
    }
}

class Way1 implements Runnable{

    private Startup startup;

    public Way1(Startup startup) {
        this.startup = startup;
    }

    public void run() {
        startup.startup1();
    }
}

class Way2 implements Runnable{

    private Startup startup;

    public Way2(Startup startup) {
        this.startup = startup;
    }

    public void run() {
        startup.startup2();
    }
}
